#include "include.h"

/*
    当前设备状态
*/
tencent_shadow_device_info esp32_state;
static const char *TAG = "app_main";
extern xQueueHandle demoks_access_net_event;
EventGroupHandle_t refresh_led_group;
TaskHandle_t TaskHandle_t_led_rotation = NULL;

static void wifi_ap_task(void *pvParameters)
{
    demoks_access_net_event_code_t event_code = DEMOSK_ACCESS_NAT_EVENT_CODE_NONE;
    uint8_t count = 0;
    bool user_online = false;
    // 开启AP+SAT模式同事打开HTTP服务器
    demoks_access_net_ap_http_init();
    while (true)
    {
        // 每次循环等待1秒
        xQueueReceive(demoks_access_net_event, (demoks_access_net_event_code_t *)&event_code, 1000 / portTICK_PERIOD_MS);

        switch (event_code)
        {
        case DEMOSK_ACCESS_NAT_EVENT_CODE_AP_STACONNECTED:
            ESP_LOGI(TAG, "用户接入了，暂停倒计时");
            user_online = true;
            break;
        case DEMOSK_ACCESS_NAT_EVENT_CODE_AP_STADISCONNECTED:
            ESP_LOGI(TAG, "用户断开了，恢复倒计时");
            user_online = false;
            break;
        case DEMOSK_ACCESS_NAT_EVENT_CODE_WIFI_ACC_SUCC:
            ESP_LOGI(TAG, "配网成功，准备断开热点");
            user_online = false;
            count += DEMOSK_ACCESS_NAT_AP_TIME_OUT;
            // 给予2秒返回数据给用户
            Delay_ms(2000);
            break;
        default:
            break;
        }

        // 清空事件
        if (event_code != DEMOSK_ACCESS_NAT_EVENT_CODE_NONE)
            event_code = DEMOSK_ACCESS_NAT_EVENT_CODE_NONE;
        // 用户不在线时进行计时
        if (!user_online)
            count++;
        if (count > DEMOSK_ACCESS_NAT_AP_TIME_OUT)
        {
            break;
        }
    }
    ESP_LOGI(TAG, "结束配网流程");
    demoks_access_net_stop();
    while (true)
    {
        Delay_ms(1000);
    }
    // 删除线程
    vTaskDelete(NULL);
}

/*

    led轮播事件队列
*/
xQueueHandle led_rotation_evt_queue;

static void led_rotation_task(void *pvParameters)
{
    printf("start led_rotation_task!\n");
    char json_msg[256];
    esp_err_t ee = ESP_FAIL;
    size_t msg_len = sizeof(json_msg);
    memset(json_msg, 0, msg_len);
    // 读取数据
    ee = lonon_nvs_get_str(NVS_LED_EVENT, LED_EVENT_JSONG, json_msg, &msg_len);
    ESP_LOGI(TAG, "get text msg! = %s", json_msg);

    if (ee == ESP_OK)
    {
        printf("lonon_nvs_set_str ok\n");
        char text[256] = {0};
        uint8_t speed = 0;
        uint32_t count = 0;
        memset(text, 0, sizeof(text));
        // 解析字符串输出 text ， speed ， count
        ee = parse_text_json(json_msg, &text, &speed, &count);
        if (ee == ESP_OK)
        {
            ESP_LOGI(TAG, "led_display_text text:%s; speed:%d; count:%d;", text, speed, count);
            strcpy(esp32_state.message, text);
            send_shadow();
            if (strlen(text) > 8)
            {
                if (count == 0)
                {
                    while (1)
                    {
                        led_display_text(base64_decode(text), speed);
                        Delay_ms(200);
                    }
                }
                else
                {
                    for (int i = 0; i < count; i++)
                    {
                        led_display_text(base64_decode(text), speed);
                        Delay_ms(200);
                    }
                }
            }
            else
                led_display_text(base64_decode(text), speed);
        }
    }
    TaskHandle_t_led_rotation = NULL;
    // 删除线程
    vTaskDelete(NULL);
}

static void led_task(void *pvParameters)
{
    char json_msg[256];

    memset(json_msg, 0, sizeof(json_msg));

    refresh_led_group = xEventGroupCreate();

    led_rotation_evt_queue = xQueueCreate(3, sizeof(json_msg)); /** 创建led消息队列 */

    printf("led_task\n");
    MAX7219_POWER_SWITCH(MAX7219_POWER_ON);
    Delay_ms(200);

    while (true)
    {
        if (TaskHandle_t_led_rotation != NULL)
            vTaskDelete(TaskHandle_t_led_rotation);

        Init_MAX7219();
        /** 这里让 led_rotation_task 一上电就直接输出储存的信息 */
        xTaskCreate(led_rotation_task, "led_rotation_task", 2048 * 2, NULL, 6, &TaskHandle_t_led_rotation);
        /** 清空 REFRESH_LED 标记 */
        xEventGroupClearBits(refresh_led_group, REFRESH_LED);
        /** 等待 REFRESH_LED 标记再次为 TRUE */
        EventBits_t bits = xEventGroupWaitBits(refresh_led_group,
                                               REFRESH_LED,
                                               pdFALSE,
                                               pdFALSE,
                                               portMAX_DELAY);
        ESP_LOGI(TAG, "执行刷新LED数据");
        Delay_ms(500);
    }
    // 删除线程
    vTaskDelete(NULL);
}

static void mqtt_task(void *pvParameters)
{
    lonon_mqtt_app_start();
    vTaskDelete(NULL);
}

static void init()
{
    /*
        初始化gpio
    */
    lonon_gpio_init();

    /*
        初始化nvs存储
    */
    lonon_nvs_flash_init();

    /**
     * 初始化demoks系统
     */
    demoks_system_init();

    /*
        初始化设备信息
    */
    esp32_state.humidity = 10;
    esp32_state.light = 1;
    esp32_state.light_intensity = 56;
    strcpy(esp32_state.message, "hello esp-idf!");
    esp32_state.motor = 0;
    esp32_state.temperature = 32;
}

void app_main()
{
    printf("app_main\n");
    init();
    xTaskCreate(wifi_ap_task, "wifi_ap_task", 2048 * 3, NULL, 5, NULL);
    xTaskCreate(led_task, "led_task", 2048, NULL, 6, NULL);
    xTaskCreate(mqtt_task, "mqtt_task", 2048, NULL, 6, NULL);
}
